﻿using AutoMapper;
using B.S.BaseData.Domain;
using B.S.BaseData.ErrorCode;
using B.S.BaseData.Read.Api.Application.Command;
using B.S.BaseData.Read.Api.Dtos;
using MediatR;
using SqlSugar;

namespace B.S.BaseData.Read.Api.Application.CommandHander
{
    public class GetDepUserRoleHander : IRequestHandler<GetDepUserRoleCommand, ApiResult<List<DepUserDto>>>
    {

        private readonly IMapper mapper;
        private readonly ISqlSugarClient db;

        public GetDepUserRoleHander(IMapper mapper, ISqlSugarClient db)
        {
            this.mapper = mapper;
            this.db = db;
        }

        /// <summary>
        /// 查询用户部门角色
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<DepUserDto>>> Handle(GetDepUserRoleCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<DepUserDto>> result = new ApiResult<List<DepUserDto>>();

            var linq = db.Queryable<User>()
                .InnerJoin<DepUser>((u, du) => u.UserId == du.UserId)
                .InnerJoin<Depment>((u, du, d) => d.DepmentId == du.DepmentId)
                .InnerJoin<UserRole>((u, du, d, ur) => ur.UserId == u.UserId)
                .InnerJoin<Role>((u, du, d, ur, r) => r.RoleId == ur.RoleId)
                .Select((u, du, d, ur, r) => new DepUserDto
                {
                    DepUserId = du.UserId,
                    UserId = u.UserId,
                    UserName = u.UserName,
                    DepmentId = d.DepmentId,
                    DepmentName = d.DepmentName,
                    RoleId = r.RoleId,
                    RoleName = r.RoleName,
                });

            result.Data = mapper.Map<List<DepUserDto>>(linq.ToList());

            return Task.FromResult(result);

        }
    }
}
